package com.kuaimacode.kframework.api.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.mybatis.mapper.user.AddressMapper;
import com.kuaimacode.kframework.mybatis.models.user.Address;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressService extends ServiceImpl<AddressMapper, Address> {

    /*public Address selectById(Long userId) {
        
        QueryWrapper<Address> qryWrapper = new QueryWrapper<>();
        qryWrapper.eq("user_id", userId);
        return baseMapper.selectOne(qryWrapper);
    }*/
    /**
     *  分页查找所有的数据
     * @param pageNum 当前页码，从1开始
     * @param pageSize  一页显示多少行
     * @return
     */
    public PageInfo<Address> findAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize,true,false,null);
        List<Address> datas = baseMapper.selectList(null);
        return new PageInfo<Address>(datas);
    }

    public List<Address> getAddressList(Long userId, Integer usual) {
        QueryWrapper<Address> qryWrapper = new QueryWrapper<>();
        qryWrapper.eq("user_id", userId);
        qryWrapper.eq("delete_state", Constant.DeleteStateEnum.NORMAL.getCode());
        if(usual != null){
            qryWrapper.eq("usual", usual);
        }
        return baseMapper.selectList(qryWrapper);
    }


    public PageInfo<Address> getAddressListPage(Long userId, Integer usual,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize,true,false,null);
        QueryWrapper<Address> qryWrapper = new QueryWrapper<>();
        qryWrapper.eq("user_id", userId);
        qryWrapper.eq("delete_state", Constant.DeleteStateEnum.NORMAL.getCode());
        if(usual != null){
            qryWrapper.eq("usual", usual);
        }
        return new PageInfo<Address>((List<Address>)baseMapper.selectList(qryWrapper));
    }

    @Transactional
    public boolean add(Address address) {
        return baseMapper.insert(address) > 0;
    }

    @Transactional
    public boolean update(Address address) {
        //User original = baseMapper.getById(user);
        return baseMapper.updateById(address) > 0;
    }

    /**
     * 获取最后插入的Id
     *
     * @return
     */
    public Long getLastInsertId(){
        return baseMapper.getLastInsertId();
    }
}